package com.springboot.service.impl;


import com.springboot.entity.OutParm;
import com.springboot.entity.TbRisReport;
import com.springboot.entity.Zthc;
import com.springboot.service.IHisInsuranceService;
import com.springboot.util.OutParmUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

@Service
public class HisInsuranceService implements IHisInsuranceService {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public OutParm tbinvoke(Class clazz,String method, TbRisReport tbRisReport) throws Exception {
        try {
            Boolean existMethod = Arrays.stream(clazz.getDeclaredMethods()).anyMatch(x -> x.getName().equals(method));
            if (!existMethod) {
                return OutParmUtil.fail(String.format("系统参数异常，未找到%s方法名称", method));
            }
            Method m = clazz.getDeclaredMethod(method, new Class[]{TbRisReport.class});
            String beanName = this.toLowerCaseFirstOne(clazz.getSimpleName().substring(1));
            OutParm result = (OutParm) m.invoke(applicationContext.getBean(beanName), tbRisReport);
            return result;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return OutParmUtil.fail(e.getTargetException().getMessage());
        } catch (Exception e) {
            return OutParmUtil.fail(String.format("系统异常:%s", e.getMessage()));
        }
    }

    @Override
    public OutParm ztinvoke(Class clazz,String method, Zthc zthc) throws Exception {
        try {
            Boolean existMethod = Arrays.stream(clazz.getDeclaredMethods()).anyMatch(x -> x.getName().equals(method));
            if (!existMethod) {
                return OutParmUtil.fail(String.format("系统参数异常，未找到%s方法名称", method));
            }
            Method m = clazz.getDeclaredMethod(method, new Class[]{Zthc.class});
            String beanName = this.toLowerCaseFirstOne(clazz.getSimpleName().substring(1));
            OutParm result = (OutParm) m.invoke(applicationContext.getBean(beanName), zthc);
            return result;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return OutParmUtil.fail(e.getTargetException().getMessage());
        } catch (Exception e) {
            return OutParmUtil.fail(String.format("系统异常:%s", e.getMessage()));
        }
    }

    private String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

}
